package com.rxt.util;

import java.util.Random;

public class PwdUtils {
    // 密码盐的位数
    private static final int SALT_DIGITS = 8;

    // 随机字符池
    private static final char[] CHAR_POOL =
            ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" + "1234567890!@#$%^&*()_+").toCharArray();

    /**
     * 随机生成 8 位的密码盐
     */
    public static String getRandomSalt() {
        StringBuilder salt = new StringBuilder();
        for (int i = 0; i < SALT_DIGITS; i++) {
            salt.append(CHAR_POOL[new Random().nextInt(CHAR_POOL.length)]);
        }
        return salt.toString();
    }

    /**
     * 密码加密
     */
    public static String encrypt(String password, String salt) {
        return Md5Utils.encrypt(password + salt);
    }

    /**
     * 密码校验
     */
    public static boolean check(String password, String salt, String saltPwd) {
        return saltPwd.equals(encrypt(password, salt));
    }

    public static void main(String[] args) {
        String salt = "!ASQsSxo";
        String pwd = "123456";
        System.out.println(encrypt(pwd, salt)); // 58d0f6908ba068a4b3bb6b882ee794d2
        System.out.println(encrypt("12345", salt)); // 7f8ff0811a4778437f3666948c69cd02
        System.out.println(check("12345", salt, "58d0f6908ba068a4b3bb6b882ee794d2"));
        System.out.println(check("123456", salt, "58d0f6908ba068a4b3bb6b882ee794d2"));
    }
}
